package com.shujia.MapReduce;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.InputSplit;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.input.FileSplit;
import org.apache.hadoop.mapreduce.lib.input.TextInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

import java.io.IOException;

public class Demo3Filter {
    public static class MyFilterMapper extends Mapper<LongWritable, Text, Text, Text> {
        @Override
        protected void map(LongWritable key, Text value, Mapper<LongWritable, Text, Text, Text>.Context context) throws IOException, InterruptedException {
            // 获取文件的输入路径
            InputSplit inputSplit = context.getInputSplit();
            FileSplit fileSplit = (FileSplit) inputSplit;
            Path path = fileSplit.getPath();
            String sPath = path.toString();
            if (sPath.contains("students")) {
                // 获取当前行的数据
                String line = value.toString();
                String[] splits = line.split(",");
                String clazz = splits[4];
                if ("理科三班".equals(clazz)) {
                    context.write(new Text(clazz), value);
                }
            }


        }
    }

    public static void main(String[] args) throws IOException, InterruptedException, ClassNotFoundException {
        Configuration conf = new Configuration();
        Job job = Job.getInstance(conf);

        job.setJobName("FilterMap");

        job.setJarByClass(Demo3Filter.class);
        // 配置Map任务
        job.setMapperClass(MyFilterMapper.class);
        job.setMapOutputKeyClass(Text.class);
        job.setMapOutputValueClass(Text.class);
        job.setInputFormatClass(TextInputFormat.class);

        // 配置输入输出路径
        FileInputFormat.addInputPath(job, new Path(args[0]));
        FileOutputFormat.setOutputPath(job, new Path(args[1]));

        job.waitForCompletion(true);
    }
    /**
     * 提交命令：
     * hadoop jar /usr/local/soft/jars/Hadoop-1.0.jar com.shujia.MapReduce.Demo3Filter /data/student/ /output1
     * 查看日志：
     * yarn logs -applicationId application_1630138143513_0003
     */
}
